package org.example.mq.brokerserver.datacenter;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.example.mq.MqApplication;
import org.example.mq.brokerserver.core.Binding;
import org.example.mq.brokerserver.core.Exchange;
import org.example.mq.brokerserver.core.ExchangeType;
import org.example.mq.brokerserver.core.MQqueue;
import org.example.mq.brokerserver.mapper.MetaMapper;

import java.io.File;
import java.util.List;

public class DatabaseManager {
    private MetaMapper metaMapper;
    public void init() throws JsonProcessingException {
        metaMapper = MqApplication.context.getBean(MetaMapper.class);
        if(checkDBExists()){
            return;
        }else {
            //建库建表并设置一些默认值
            File dataDirk = new File("./data");
            dataDirk.mkdirs();
            createTable();
            createDefault();
            System.out.println("初始化数据库完成");
        }
    }
    public void deleteDatabase(){
        File file = new File("./data/meta.db");
        if(file.delete()){
            System.out.println("删除数据库成功！");
        }else {
            System.out.println("删除数据库失败！");
        }
    }
    private void createDefault() throws JsonProcessingException {
        Exchange exchange = new Exchange();
        exchange.setAutoDelete(false);
        exchange.setDurable(true);
        exchange.setName("default");
        exchange.setType(ExchangeType.DIRECT);
        exchange.setOptions("{}");
        metaMapper.insertExchange(exchange);
        System.out.println("插入exchange数据成功");
    }

    private void createTable() {
        metaMapper.createBindingTable();
        metaMapper.createExchangeTable();
        metaMapper.createMQqueueTable();
    }

    private boolean checkDBExists() {
        File file = new File("./data/meta.db");
        if(file.exists()){
            return true;
        }
        return false;
    }
    public void createExchangeTable(){
        metaMapper.createExchangeTable();
    }
public void createMQqueueTable(){
  metaMapper.createMQqueueTable();}
public void createBindingTable(){
     metaMapper.createBindingTable();
}
public //插入和删除
 void insertExchange(Exchange exchange){
     metaMapper.insertExchange(exchange);
 }
public void insertQueue(MQqueue mQqueue){
    metaMapper.insertQueue(mQqueue);
 }
public int insertBinding(Binding binding){
    return metaMapper.insertBinding(binding);
}
public void deleteExchange(String name){
        metaMapper.deleteExchange(name);
}
public void deleteQueue(String name){
        metaMapper.deleteQueue(name);
}
public void deleteBinding(Binding binding){
        metaMapper.deleteBinding(binding);
}
public List<Exchange> selectAllExchange(){
        return metaMapper.selectAllExchange();
}
public List<MQqueue> selectAllMQqueue(){
        return metaMapper.selectAllMQqueue();
}
public List<Binding> selectAllBinding(){
        return metaMapper.selectAllBinding();
}
}
